package com.haoxuer.discover.user.oauth.impl;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haoxuer.discover.user.oauth.api.OauthHandler;
import com.haoxuer.discover.user.oauth.domain.OauthResponse;
import com.haoxuer.discover.user.oauth.domain.TokenResponse;
import com.haoxuer.discover.user.oauth.domain.WeiboUser;
import com.haoxuer.utils.http.Connection;
import com.haoxuer.utils.http.HttpConnection;
import java.io.IOException;

public class WeiBoHander implements OauthHandler {
  @Override
  public void setKey(String key) {

  }

  @Override
  public void setSecret(String secret) {

  }

  @Override
  public OauthResponse login(String access_token, String openid) {
    OauthResponse result = null;

    try {
      Connection con = HttpConnection.connect("https://api.weibo.com/2/account/get_uid.json");
      con.data("access_token", access_token);
      con.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");
      String backjson = null;
      backjson = con.execute().body();
      JsonParser parser = new JsonParser();
      JsonElement e = parser.parse(backjson);
      String uid = e.getAsJsonObject().get("uid").getAsString();

      Connection infocon = HttpConnection.connect("https://api.weibo.com/2/users/show.json");
      infocon.data("access_token", access_token);
      infocon.data("uid", uid);
      infocon.header("User-Agent",
          "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");
      String uifos = infocon.execute().body();
      Gson gson = new Gson();
      result = gson.fromJson(uifos, WeiboUser.class);
    } catch (IOException e) {
      e.printStackTrace();
    }


    return result;
  }

  @Override
  public TokenResponse getToken(String code) {
    return null;
  }
}
